/* 
 * Copyright (c) 2021, CENTRIN.CIYUN.LTD. All rights reserved.
 */
package com.cory.api.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestHeader;
import com.cory.api.core.ApiTokenCache;
import com.cory.api.domain.ApiPrincipal;
import com.cory.boot.base.BaseController;
import com.cory.boot.domain.CustomRuntimeException;

/**
 * @author xiongcong
 * @date 2021-05-22
 */
@Slf4j
public class ApiController extends BaseController {
    
    private ThreadLocal<ApiPrincipal> principalLocal = new ThreadLocal<ApiPrincipal>();
    
    @ModelAttribute  
    public ApiPrincipal token(@RequestHeader String token) {  
        log.info("token：" + token);
        ApiPrincipal principal = ApiTokenCache.getPrincipal(token);
        if (principal == null) {
            throw new CustomRuntimeException(999, "token已失效");
        }
        principalLocal.set(principal);
        return principal;
    } 
    
    protected ApiPrincipal getPrincipal() {
        return this.principalLocal.get();
    }
    
    protected Integer getUserId() {
        checkLogin();
        return this.principalLocal.get().getUserId();
    }
    
    public boolean isLogin() {
        return this.principalLocal.get().getUserId() != null;
    }
    
    public void checkLogin() {
        if (!isLogin()) {
            throw new CustomRuntimeException(888, "用户未登录");
        }
    }
    
}
